package cnn.testmpt;

import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class Condition {
    private static Map<Class, SerializedLambda> CLASS_LAMDBA_CACHE = new ConcurrentHashMap<>();

    /***
     * 转换方法引用为属性名
     * @param functions
     * @return
     */
    public static void eq(MyFunction ... functions) {
        for (MyFunction fun : functions) {
            System.out.println("");
            System.out.println("传入的实现类：" + fun.getImplClass());
            System.out.println("传入的方法名：" + fun.getImplMethodName());
            System.out.println("传入的参数值：" + fun.get());
            System.out.println("传入数据类型：" + fun.get().getClass());
        }
    }
//
    public static <T,R> String convertToFieldName(IGetter<T> fn) {
        SerializedLambda lambda = getSerializedLambda(fn);
        String methodName = lambda.getImplMethodName();
        System.out.println(methodName);

        return methodName;
    }

//    public static <T, U> String convertToFieldName(ISetter<T, U> fn) {
//        SerializedLambda lambda = getSerializedLambda(fn);
//        String methodName = lambda.getImplMethodName();
//        if(!methodName.startsWith("set")) {
//            log.warn("无效的setter方法：" + methodName);
//        }
//        return StringUtils.capitalize(methodName.replace("set", ""));
//    }
    /**
     * 关键在于这个方法
     */
    public static SerializedLambda getSerializedLambda(Serializable fn) {
        SerializedLambda lambda = CLASS_LAMDBA_CACHE.get(fn.getClass());
        if(lambda == null) {
            try {
                Method method = fn.getClass().getDeclaredMethod("writeReplace");
                method.setAccessible(Boolean.TRUE);
                lambda = (SerializedLambda) method.invoke(fn);
                CLASS_LAMDBA_CACHE.put(fn.getClass(), lambda);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return lambda;
    }
}

